<template>
  <canvas ref="canvasRef"></canvas>
</template>
  
<script setup>
import {
  WebGLRenderer,
  Scene,
  PerspectiveCamera,
  BoxGeometry,
  MeshPhongMaterial,
  Mesh,
  DirectionalLight,
} from "three";
import { handleError, onMounted, ref } from "vue";

const canvasRef = ref(null);

onMounted(() => {
  // 创建渲染器
  const renderer = new WebGLRenderer({ canvas: canvasRef.value });

  // 创建场景
  const scene = new Scene();

  // 创建镜头
  const camera = new PerspectiveCamera(75, 2, 0.1, 5); //镜头的角度、宽高比例

  // 创建几何体
  const geometry = new BoxGeometry(1, 1, 1);

  // 创建材质
  const material1 = new MeshPhongMaterial({ color: 0x44aa88 });
  const material2 = new MeshPhongMaterial({ color: 0xff6799 });
  const material3 = new MeshPhongMaterial({ color: 0xff6700 });

  // 创建网格
  const cube1 = new Mesh(geometry, material1);
  cube1.position.x = -2;
  const cube2 = new Mesh(geometry, material2);
  const cube3 = new Mesh(geometry, material3);
  cube3.position.x = 2;
  const cubes = [cube1, cube2, cube3];
  scene.add(cube1);
  scene.add(cube2);
  scene.add(cube3);

  // 创建光源
  const light = new DirectionalLight(0xffffff, 1);
  light.position.set(-1, 2, 4);
  scene.add(light);

  camera.position.z = 2;

  //   渲染
  renderer.render(scene, camera);
  const rotate = (time) => {
    time = time * 0.001;
    renderer.render(scene, camera);
    // 自动旋转
    cubes.map((item) => {
      item.rotation.x = time;
      item.rotation.y = time;
    });

    // 屏幕窗口变化
    const handleResize = () => {
      const canvas = renderer.domElement; //获取到canvas
      // console.log(canvas.clientWidth);
      // console.log(canvas.offsetWidth);
      camera.zoom = 0.5 * (canvas.clientWidth / canvas.clientHeight);
      camera.aspect = canvas.clientWidth / canvas.clientHeight; //修改宽高比例
      camera.updateProjectionMatrix(); //通知更新
      // 还有锯齿
      renderer.setSize(canvas.clientWidth, canvas.clientHeight);
    };
    handleResize();
    window.addEventListener("resize", handleResize);
    window.requestAnimationFrame(rotate);
  };
  window.requestAnimationFrame(rotate); //16.7ms
});
</script>
  
<style scoped>
canvas {
  display: block;
  width: inherit;
  height: inherit;
}
</style>